jQuery.fn.decHTML = function() {
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.text();
    me.text("&nbsp;");
    me.append(html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
  });
};

$(function () {
	sections = ['infra','diskstorage','tapestorage','psystems','netcomms','iptelephony','vrouter'];
	sectionsText = ['Cloud server system','Cloud Storage','Cloud Archive','Cloud power system','Cloud Communications','Cloud phone','Cloud Router & Firewall'];
	products = [ ];
	products['infra'] = [] ;
	products['infra']['parameters'] = ['cpu','ram','infra-term'];
	products['infra']['slides'] = [] ;
	products['infra']['priceUrl'] = [];
	products['infra']['slides']['cpu'] = produceScale(0, 30.1, 0.1, "&nbsp;GHz");
	products['infra']['priceUrl']['cpu'] = "/priceget/infra/1/";
	products['infra']['slides']['ram'] = produceScale(0, 100, 1, "&nbsp;GB");
	products['infra']['priceUrl']['ram'] = "/priceget/infra/0/1";
	products['infra']['slides']['infra-term'] =  ['1&nbsp;г.', '2&nbsp;г.', '3&nbsp;г.', '4&nbsp;г.', '5&nbsp;г.'];

	products['diskstorage'] = [] ;
	products['diskstorage']['parameters'] = ['diskstorage-space','diskstorage-term'];
	products['diskstorage']['slides'] = [];
	products['diskstorage']['slides']['diskstorage-space'] =  produceScale(0, 1000, 10, "&nbsp;GB");
	products['diskstorage']['slides']['diskstorage-term'] =  ['1&nbsp;г.', '2&nbsp;г.', '3&nbsp;г.', '4&nbsp;г.', '5&nbsp;г.'];
	products['diskstorage']['priceUrl'] = [];
	products['diskstorage']['priceUrl']['diskstorage-space'] = "/priceget/diskstorage/10/";
	
	products['tapestorage'] = [] ;
	products['tapestorage']['parameters'] = ['tapestorage-space','tapestorage-term'];
	products['tapestorage']['slides'] = [];
	products['tapestorage']['slides']['tapestorage-space'] =  produceScale(0, 1000, 10, "&nbsp;GB");
	products['tapestorage']['slides']['tapestorage-term'] =  ['1&nbsp;г.', '2&nbsp;г.', '3&nbsp;г.', '4&nbsp;г.', '5&nbsp;г.'];
	products['tapestorage']['priceUrl'] = [];
	products['tapestorage']['priceUrl']['tapestorage-space'] = "/priceget/tapestorage/10/";	

	products['psystems'] = [] ;
	products['psystems']['parameters'] = ['psystems-size','psystems-term'];
	products['psystems']['slides'] = [];
	products['psystems']['slides']['psystems-size'] =  produceScale(0, 100, 5, "&nbsp;rPerf");
	products['psystems']['slides']['psystems-term'] =  ['1&nbsp;г.', '2&nbsp;г.', '3&nbsp;г.', '4&nbsp;г.', '5&nbsp;г.'];
	products['psystems']['priceUrl'] = [];
	products['psystems']['priceUrl']['psystems-size'] = "/priceget/psystems/1/";

	
	products['netcomms'] = [] ;
	products['netcomms']['parameters'] = ['netcomms-bwbg', 'netcomms-bwint' ,'netcomms-term'];
	products['netcomms']['slides'] = [];
	products['netcomms']['slides']['netcomms-bwbg'] =  produceScale(0, 100, 10, "&nbsp;Mbps");
	products['netcomms']['slides']['netcomms-bwint'] =  produceScale(0, 10, 1, "&nbsp;Mbps");
	products['netcomms']['slides']['netcomms-term'] =  ['1&nbsp;г.', '2&nbsp;г.', '3&nbsp;г.', '4&nbsp;г.', '5&nbsp;г.'];
	products['netcomms']['priceUrl'] = [];
	products['netcomms']['priceUrl']['netcomms-bwbg'] = "/priceget/netcomms/10/"
	products['netcomms']['priceUrl']['netcomms-bwint'] = "/priceget/netcomms/1/"

	products['iptelephony'] = [] ;
	products['iptelephony']['parameters'] = ['iptelephony-basic', 'iptelephony-adv', 'iptelephony-secretary', 'iptelephony-mobile'   ,'iptelephony-term'];
	products['iptelephony']['slides'] = [];
	products['iptelephony']['slides']['iptelephony-basic'] =  produceScale(0, 100, 1, "&nbsp;");
	products['iptelephony']['slides']['iptelephony-adv'] =  produceScale(0, 100, 1, "&nbsp;");
	products['iptelephony']['slides']['iptelephony-secretary'] =  produceScale(0, 10, 1, "&nbsp;");
	products['iptelephony']['slides']['iptelephony-mobile'] =  produceScale(0, 100, 1, "&nbsp;");
	products['iptelephony']['slides']['iptelephony-term'] =  ['1&nbsp;г.', '2&nbsp;г.', '3&nbsp;г.', '4&nbsp;г.', '5&nbsp;г.'];
	products['iptelephony']['priceUrl'] = [];
	products['iptelephony']['priceUrl']['iptelephony-basic'] = "/priceget/iptelephony/1/";
	products['iptelephony']['priceUrl']['iptelephony-adv'] = "/priceget/iptelephony/0/1";
	products['iptelephony']['priceUrl']['iptelephony-secretary'] = "/priceget/iptelephony/0/0/1/";
	products['iptelephony']['priceUrl']['iptelephony-mobile'] = "/priceget/iptelephony/2";
	
	products['vrouter'] = [] ;
	products['vrouter']['parameters'] = ['vrouter-size','vrouter-term'];
	products['vrouter']['slides'] = [];
	products['vrouter']['slides']['vrouter-size'] =  produceScale(0, 5, 1, "&nbsp;");
	products['vrouter']['slides']['vrouter-term'] =  ['1&nbsp;г.', '2&nbsp;г.', '3&nbsp;г.', '4&nbsp;г.', '5&nbsp;г.'];
	products['vrouter']['priceUrl'] = [];
	products['vrouter']['priceUrl']['vrouter-size'] = "/priceget/vrouter/1/";
	progress = [];
	price  = [];
	myi = 0;
	$("body").attr("id","calculator");
	$("#node-88 #edit-submit").attr("value","Изпрати");
	$("#main_content .node").addClass("left");
	$("#main_content .node .right").insertBefore("#main_content .node");
	$(".webform-client-form #edit-actions").appendTo(".take_it h1:first");
	$(".take_it h1:first").insertAfter(".gray h2:last");
	$("#edit-submit").click(function() { $(".webform-client-form").submit(); })
	$('.blue:gt(0)').hide();
	$(".webform-component-textfield:gt(2)").hide();
	$("#webform-component-name, #webform-component-company, #webform-component-phone").show();
	initializeSection(sections[0]);
	for (i in sections) {
			sectionTitle = $(".sectionTitle:first").clone();
			
			sectionTitle.addClass("sectionTitle"+sections[i]);
			sectionTitle.text( sectionsText[i] );
			sectionTitle.attr( "section", sections[i] );

			sectionTitle.show();
			sectionTitle.click( function() {
						section = $(this).attr("section");
						if ( !$(this).hasClass("expanded") ) { 
							  						
							$("."+section+"-div").parent().slideDown( function() { initializeSection(section); });
							$(this).addClass("expanded");
						} else {
							deinitializeSection(section);
							$("."+section+"-div").parent().slideUp();
							$(this).removeClass("expanded");
						}
					});
			sectionTitle.appendTo($(".take_more_title"));
	}

	
	  $(".sectionTitleinfra").addClass("expanded");
  fixedElement = $('.right .gray:first');
  var top = fixedElement.offset().top - parseFloat( fixedElement.css('marginTop').replace(/auto/, 0));
  fixedElement.css('position','absolute');  
  $(window).scroll(function (event) {
    var y = $(this).scrollTop();
    if (y >= top) {
      fixedElement.css('position','fixed');
      fixedElement.css('top','20px');
      fixedElement.css('width','300px');
    } else {
      fixedElement.css('position','absolute');
    }
  });

});

function scaleCleanUp( jqObject ) {
	
	$(".jslider-scale", jqObject).each( function() {
		marks = $(this).find("ins");
		//if ( marks.text().match("[6,8] Ghz") ) $(this).hide();
		//if ( marks.text().match("\\.[1-9]") ) $(this).hide();
		if ( marks.size() > 20 ) {
			i = 0;
			div = Math.round(marks.size()/10);
			marks.each( function() { 
				if ( i % div != 0 ) $(this).parent().hide();  
				i++;
			});
		}
		});
}

function calcPriceUpdate( type ) {
	
		price[type] = 0;
		for ( i in products[type]['parameters'] ) {
			parameter = products[type]['parameters'][i];
			if ( products[type]['priceUrl'] !== undefined && products[type]['priceUrl'][parameter] !== undefined ) {
				getPrice( products[type]['priceUrl'][parameter] , type );
				selectedTerm = parseInt($("#edit-submitted-"+type+"-term" ).attr('value'));	
				selectedParam = parseFloat($("#edit-submitted-"+parameter ).attr('value'));
				priceSingleParam = $("#priceCache").find("div[url='"+products[type]['priceUrl'][parameter]+"'] .field-field-price"+selectedTerm+" .field-item").html();
				if (priceSingleParam !== null ) priceSingleParam = priceSingleParam.replace('&amp;nbsp;', "");
				priceFloat = parseFloat(selectedParam) * parseFloat(priceSingleParam); 
				if ( priceFloat > 0.1 ) price[type] +=  Math.round (priceFloat * 100 )/ 100;
				
				}
			}
	priceTotal = 0;
	for (i in price) { priceTotal += price[i]; }
	priceTotal = parseInt( priceTotal * 100 ) / 100;
	$("#edit-submitted-price").attr("value", priceTotal);
	$('.box_gr').html( priceTotal );
			 	
}

function getPrice( priceUrl, type ) {
	
	if ( $('#priceCache div[url="'+priceUrl+'"]').size() == 0 && 
			(progress[priceUrl] == undefined ||  progress[priceUrl]  == 0 ) ) {
		progress[priceUrl]  = 1;
		jQuery.ajax({
		         url:    priceUrl ,
		         success:  function( data ) {
				channel =  $('channel:first description', data);
				divCache = $("<div></div>");
				divCache.attr("url", priceUrl);
				divCache.html( channel.text() );
				$("#priceCache").append(divCache);
				if (! $.browser.msie ) $('#priceCache div:last').decHTML();
				progress[priceUrl]  = 0;
				progSum = 0;
				for (i in progress) progSum+= progress[i];
				if (progSum == 0 ) calcPriceUpdate( type );
  			},
        		 async:   true
 	 	 });  
	}

}

function produceScale( start, end, step, metric) {
	result = [];
	for ( i = start; i <= end; i = i + step) {
		result.push( ( Math.round( parseFloat(i) *10 ) ) /10+ metric );
	}
	return result;
}

function initializeSection( section ) {
	$("."+section+"-title:first").prependTo( $("."+section+"-div"));
	for (par in products[section]['parameters']) {
		parName = products[section]['parameters'][par];
		parScale = products[section]['slides'][ parName ];
		for ( pari in parScale ) {
			label = parScale[pari];
			if ($("#node-88").size()<1) parScale[pari] = label.replace("г", "yr");
		}
		$("#webform-component-" + parName).appendTo("."+section+"-div");
		//if ( parseFloat(parScale[0]) != 0 ) val = 1; else   val = 2;
		if (parName.match("term")) val = 1; else val = 0;	
 		$("#edit-submitted-" + parName ).attr("value", val);
		$("#edit-submitted-" + parName ).parent().parent().show();
		$("#edit-submitted-" + parName ).slider({ 
			from: 1, 
			to: parScale.length, 
			step: 1, 
			value: val,
			round: 1, 
			smooth: false,
			dimension: '', 
		  	scale: parScale,
			skin: "round",
			onstatechange: function(value) { 
					calcPriceUpdate(section);
				}
		});
		scaleCleanUp( $("#edit-submitted-" + parName ).parent().parent() );
		if ( $("#edit-submitted-" + parName ).attr("disvalueor") > 0) {
				valor = $("#edit-submitted-" + parName ).attr("disvalueor");
				$("#edit-submitted-" + parName ).slider("value", valor);
				calcPriceUpdate(section);
			}
		}
}

function deinitializeSection( section ) {
	for (par in products[section]['parameters']) {
		parName = products[section]['parameters'][par];
		val = 0;	
		//$("#edit-submitted-" + parName ).attr("disvalue", $("#edit-submitted-" + parName ).attr("value") );
		$("#edit-submitted-" + parName ).attr("disvalueor", $("#edit-submitted-" + parName ).attr("valueor") );
 		$("#edit-submitted-" + parName ).attr("value", val);
		$("#edit-submitted-" + parName ).slider("value", val);
	}
	calcPriceUpdate(section);
}
	
